import { Button, Card, Form, Input, message, Space, Table } from 'antd'
import { SearchOutlined, EditOutlined, DeleteOutlined, ExclamationCircleFilled } from '@ant-design/icons'
import React, { useCallback, useEffect, useState } from 'react'
import { ColumnsType } from 'antd/lib/table'
import { batchRemove, deleteHospitalSetItem, getHospitalSetList } from '@/api/hospital/hospitalSet'
import { IHospitalSetItem, IHospitalSetList } from '@/api/hospital/model/hospitalSetTypes'
import { useNavigate } from 'react-router-dom'
import confirm from 'antd/lib/modal/confirm'

export default function HospitalSet() {
    const navigate = useNavigate()
    const columns: ColumnsType<any> = [
        {
            title: '序号',
            fixed: 'left',
            width: 60,
            align: 'center',
            render(value: any, rows: any, index: number) {
                return (current - 1) * pageSize + index + 1
            }
        },
        {
            title: '医院名称',
            dataIndex: 'hosname'
        },
        {
            title: '医院编号',
            dataIndex: 'hoscode'
        },
        {
            title: 'api基础路径',
            dataIndex: 'apiUrl'
        },
        {
            title: '签名',
            dataIndex: 'signKey'
        },
        {
            title: '联系人姓名',
            dataIndex: 'contactsName'
        },
        {
            title: '联系人手机号',
            dataIndex: 'contactsPhone'
        },
        {
            title: '操作',
            fixed: 'right',
            width: 100,
            render(rows: IHospitalSetItem) {
                return (
                    <Space>
                        <Button type="primary" icon={<EditOutlined />} onClick={() => navigate('/syt/hospital/hospitalSet/edit/' + rows.id)}></Button>
                        <Button type="primary" danger icon={<DeleteOutlined />} onClick={() => deleteHandler(rows.id)}></Button>
                    </Space>
                )
            }
        }
    ]
    // 声明状态
    let [hospitalSetList, setHospitalSetList] = useState<IHospitalSetList>() // 医院设置分页列表数据
    let [current, setCurrent] = useState<number>(1) // 当前页
    let [pageSize, setPageSize] = useState<number>(3) // 每页显示条数
    let [total, setTotal] = useState<number>(10) // 总条数
    let [hosname, setHosname] = useState<string>() // 医院名称
    let [hoscode, setHoscode] = useState<string>() // 医院编号
    let [loading, setLoading] = useState<boolean>(false) // loading控制
    let [ids, setIds] = useState<React.Key[]>([])
    // 创建form ，给Form 绑定form属性，form.getFieldsValue获取数据 form.resetFieldsValue重置数据
    const [form] = Form.useForm()
    // 查询
    const onFinish = useCallback(() => {
        let { hosname, hoscode } = form.getFieldsValue()
        setHosname(hosname)
        setHoscode(hoscode)
        setCurrent(1)
    }, [])
    // 清空功能
    const reset = useCallback(() => {
        // 1. 将hosname hoscode 状态设置为undefined
        setHoscode(undefined)
        setHosname(undefined)
        // 2. 将表单清空
        form.resetFields()
        // 3. 当前页设置为1
        setCurrent(1)
    }, [])
    /**
     * 根据id删除
     */
    const deleteHandler = useCallback((id: string | number) => {
        confirm({
            title: '删除?',
            icon: <ExclamationCircleFilled />,
            content: '确定删除医院设置么？',
            async onOk() {
                // 1. 删除
                await deleteHospitalSetItem(id)
                // 2. 提示
                message.success('删除成功')
                //3 .更新列表
                _getHospitalSetList()
            }
        });

    }, [])

    /**
     * 批量删除
     */
    const batchRemoveHandler = useCallback(() => {
        confirm({
            title: '删除?',
            icon: <ExclamationCircleFilled />,
            content: '确定删除医院设置么？',
            async onOk() {
                await batchRemove(ids)
                message.success('批量删除成功')
                _getHospitalSetList()
                // 清空ids状态
                setIds([])
            }
        });
    },[ids])

    // 获取医院分页列表数据，参数： page:当前页 limit：每页显示条数 hosname:医院名称 hoscode:医院编号
    const _getHospitalSetList = async () => {

        // 开启loading
        setLoading(true)
        let { records, total } = await getHospitalSetList({ page: current, limit: pageSize, hosname, hoscode })
        // 设置医院列表状态数据
        setHospitalSetList(records)
        // 设置总条数
        setTotal(total)
        // 关闭loading
        setLoading(false)
    }
    useEffect(() => {
        _getHospitalSetList()
    }, [current, pageSize, hosname, hoscode])
    return (
        <Card>
            {/* 1. Form表单 */}
            <Form
                form={form}
                layout='inline'
                name="basic"
                onFinish={onFinish}
            >
                <Form.Item
                    name="hosname"
                >
                    <Input placeholder='医院名称' />
                </Form.Item>

                <Form.Item
                    name="hoscode"
                >
                    <Input placeholder='医院编号' />
                </Form.Item>

                <Form.Item>
                    <Space>
                        <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                            查询
                        </Button>
                        <Button disabled={!hosname && !hoscode} onClick={reset}>清空</Button>
                    </Space>
                </Form.Item>
            </Form>
            {/* 2. 按钮 */}
            <Space className="mt20">
                <Button type="primary" onClick={() => navigate('/syt/hospital/hospitalSet/add')}>添加</Button>
                <Button disabled={ids.length === 0} onClick={batchRemoveHandler}>批量删除</Button>
            </Space>
            {/* 3. 表格 */}
            <Table
                scroll={{ x: 1300 }}
                loading={loading}
                className="mt20"
                rowKey={'id'}
                columns={columns}
                dataSource={hospitalSetList}
                pagination={{
                    current,
                    pageSize,
                    total,
                    showQuickJumper: true,
                    showSizeChanger: true,
                    pageSizeOptions: [5, 10, 20],
                    onChange: (page: number, pageSize: number) => {
                        setCurrent(page)
                        setPageSize(pageSize)
                    }
                }}
                rowSelection={{
                    onChange: (selectedRowKeys: React.Key[]) => {
                        // console.log('selectedRowKeys: ',selectedRowKeys)
                        // 将要删除的id存储成状态 ids
                        setIds(selectedRowKeys)
                    }
                }}
            />
        </Card>
    )
}
